package com.haiheng.moudule_visualinventoryrobot.fragment

import android.content.Context
import android.hardware.usb.UsbDevice
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.haiheng.library_base.adapter.BaseAdapter
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.moudule_visualinventoryrobot.R
import com.haiheng.moudule_visualinventoryrobot.adpter.MultiCameraAdapter
import com.haiheng.moudule_visualinventoryrobot.databinding.DemoMultiCameraFragmentBinding
import com.jiangdg.ausbc.MultiCameraClient
import com.jiangdg.ausbc.base.MultiCameraFragment
import com.jiangdg.ausbc.callback.ICameraStateCallBack
import com.jiangdg.ausbc.callback.ICaptureCallBack
import com.jiangdg.ausbc.camera.CameraUVC
import com.jiangdg.ausbc.camera.bean.CameraRequest
import com.jiangdg.ausbc.utils.ToastUtils
import com.jiangdg.ausbc.widget.AspectRatioTextureView

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2024/3/1 0001
 * @Version: 1.0
 */
//class DemoMultiCameraFragment :Fragment() {
class DemoMultiCameraFragment : CustomMultiCameraFragment(), ICameraStateCallBack {
    private lateinit var mViewBinding: DemoMultiCameraFragmentBinding
    private lateinit var mAdapter: MultiCameraAdapter
    private val mCameraList by lazy {
        ArrayList<MultiCameraClient.ICamera>()
    }
    private val mHasRequestPermissionList by lazy {
        ArrayList<MultiCameraClient.ICamera>()
    }

    override fun onCameraAttached(camera: MultiCameraClient.ICamera) {
        mAdapter.getData().add(camera)
        mAdapter.notifyItemInserted(mAdapter.getData().size - 1)
        mViewBinding.multiCameraTip.visibility = View.GONE
    }

    override fun onCameraDetached(camera: MultiCameraClient.ICamera) {
        mHasRequestPermissionList.remove(camera)
        for ((position, cam) in mAdapter.getData().withIndex()) {
            Log.e(
                "ddd hwz",
                "deviceId:${cam.getUsbDevice().deviceId}  cameraId:${camera.getUsbDevice().deviceId}"
            )
            if (cam.getUsbDevice().deviceId == camera.getUsbDevice().deviceId) {
                camera.closeCamera()
                mAdapter.getData().removeAt(position)
                mAdapter.notifyItemRemoved(position)
                break
            }
        }
        if (mAdapter.getData().isEmpty()) {
            mViewBinding.multiCameraTip.visibility = View.VISIBLE
        }
    }

    override fun generateCamera(ctx: Context, device: UsbDevice): MultiCameraClient.ICamera {
        return CameraUVC(ctx, device)
    }

    override fun onCameraConnected(camera: MultiCameraClient.ICamera) {
        for ((position, cam) in mAdapter.getData().withIndex()) {
            if (cam.getUsbDevice().deviceId == camera.getUsbDevice().deviceId) {
                var holder = mViewBinding.multiCameraRv.findViewHolderForLayoutPosition(position)
                val textureView =
                    holder?.itemView?.findViewById<AspectRatioTextureView>(R.id.multi_camera_texture_view)
                cam.openCamera(textureView, getCameraRequest())
                cam.setCameraStateCallBack(this)
                break
            }
        }
        // request permission for other camera
        mAdapter.getData().forEach { cam ->
            val device = cam.getUsbDevice()
            if (!hasPermission(device)) {
                mHasRequestPermissionList.add(cam)
                requestPermission(device)
                return@forEach
            }
        }
    }

    override fun onCameraDisConnected(camera: MultiCameraClient.ICamera) {
        camera.closeCamera()
    }


    override fun onCameraState(
        self: MultiCameraClient.ICamera,
        code: ICameraStateCallBack.State,
        msg: String?
    ) {
        if (code == ICameraStateCallBack.State.ERROR) {
            ToastUtils.show(msg ?: "open camera failed.")
        }
        for ((position, cam) in mAdapter.getData().withIndex()) {
            if (cam.getUsbDevice().deviceId == self.getUsbDevice().deviceId) {
                mAdapter.notifyItemChanged(position, "switch")
                break
            }
        }
    }

    override fun initLoad() {
        super.initLoad()
    }


    override fun initView() {
//        super.initView()
        openDebug(true)
        mAdapter = MultiCameraAdapter()
        mAdapter.setNewData(mCameraList)
        mViewBinding.multiCameraRv.adapter = mAdapter
        mViewBinding.multiCameraRv.layoutManager = GridLayoutManager(requireContext(), 2)

        mAdapter.setOnItemChildClickListener(object : BaseAdapter.OnItemChildClickListener {
            override fun onItemChildClick(
                view: View,
                holder: BaseAdapter.ViewBindHolder,
                position: Int
            ) {
                val camera = mAdapter.getItem(position)
                when (view.id) {
                    R.id.multi_camera_capture_image -> {
                        camera.captureImage(object : ICaptureCallBack {
                            override fun onBegin() {}

                            override fun onError(error: String?) {
                                ToastUtils.show(error ?: "capture image failed")
                            }

                            override fun onComplete(path: String?) {
                                ToastUtils.show(path ?: "capture image success")
                            }
                        })
                    }

                    R.id.multi_camera_capture_video -> {
                        if (camera.isRecording()) {
                            camera.captureVideoStop()
                            return
                        }
                        camera.captureVideoStart(object : ICaptureCallBack {
                            override fun onBegin() {
                                mAdapter.notifyItemChanged(position, "video")
                            }

                            override fun onError(error: String?) {
                                mAdapter.notifyItemChanged(position, "video")
                                ToastUtils.show(error ?: "capture video failed")
                            }

                            override fun onComplete(path: String?) {
                                mAdapter.notifyItemChanged(position, "video")
                                ToastUtils.show(path ?: "capture video success")
                            }
                        })
                    }

                    else -> {
                    }
                }

            }
        })

    }

    override fun initViewModel(): BaseViewModel? {

        return null
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mViewBinding = DemoMultiCameraFragmentBinding.inflate(inflater, container, false)
        return mViewBinding.root
    }
//    override fun getRootView(inflater: LayoutInflater, container: ViewGroup?): View {
//        mViewBinding = DemoMultiCameraFragmentBinding.inflate(inflater, container, false)
//        return mViewBinding.root
//    }

    private fun getCameraRequest(): CameraRequest {
        return CameraRequest.Builder()
            .setPreviewWidth(640)
            .setPreviewHeight(480)
            .create()
    }

}